﻿/*
LICENCE___________________________________________________________________
    Copyright (C) 2012 Reverdy Sylvain

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License along
    with this program; if not, write to the Free Software Foundation, Inc.,
    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
FIN LICENCE______________________________________________________________
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using Merise_designer.Objets;
using Merise_designer.Methodes;
using System.IO;

namespace Merise_designer.ExportTools
{
    public class Export
    {
        private static String export_path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + Path.DirectorySeparatorChar +Configuration.appFolder +Path.DirectorySeparatorChar + "Export" + Path.DirectorySeparatorChar;
        public static String getExportPath()
        {
            return export_path;
        }


        public void exportToXml(ObjetsCommun controller,String pathFileName)
        {
            List<CL_DictionnaireDeDonnees> data;

            XmlTextWriter myXmlTextWriter = new XmlTextWriter(pathFileName, null);
            myXmlTextWriter.Formatting = Formatting.Indented;
            myXmlTextWriter.WriteStartDocument(false);

            myXmlTextWriter.WriteComment("XML généré depuis Merise designer");

            //ROOT
            myXmlTextWriter.WriteStartElement("MLD");

            //ENTITES
            #region Entites
            List<CL_Entite> myEntites = controller.m_objets.Item1.getAllEntites();//récupère toutes les entités
            //DataSet donnees;

            foreach (CL_Entite ent in myEntites)
            {
                //Attributs
                data = controller.m_objets.Item1.afficheContenuMLD_of(ent, controller.m_objets.Item2, controller.m_objets.Item3);
                data.Sort(CL_DictionnaireDeDonnees.idComparaison);
                if (data.Count > 0)
                {

                    myXmlTextWriter.WriteStartElement("TABLE", null);
                    //myXmlTextWriter.WriteAttributeString("id", ent.Id);
                    myXmlTextWriter.WriteAttributeString("name", ent.Name);
                    myXmlTextWriter.WriteAttributeString("codeName", ent.CodeName);



                    foreach (CL_DictionnaireDeDonnees d in data)
                    {
                        myXmlTextWriter.WriteStartElement("ATTRIBUT", null);
                        //myXmlTextWriter.WriteAttributeString("id", d.id.ToString());
                        myXmlTextWriter.WriteAttributeString("nom", d.nom);
                        myXmlTextWriter.WriteAttributeString("code", d.code);
                        myXmlTextWriter.WriteAttributeString("type", d.stringType);
                        myXmlTextWriter.WriteAttributeString("Required", d.O.ToString());
                        if (d.isForeignKey)
                        {
                            myXmlTextWriter.WriteAttributeString("FOREIGN_KEY_OF", !d.EntIsNull() ? controller.getEntite(d.idEntite).Name : (!d.AssoIsNull() ? controller.getAssociation(d.idAsso).Name : null));
                        }
                        else
                        {
                            if (d.pk) myXmlTextWriter.WriteAttributeString("PRIMARY_KEY_OF", controller.getEntite(d.idEntite).Name);
                        }

                        myXmlTextWriter.WriteEndElement();
                    }

                    myXmlTextWriter.WriteEndElement();
                }
            }
            #endregion

            //ASSOCIATIONS
            #region Association
            List<CL_Association> myAssociations = controller.m_objets.Item3.getAllAssociations();//récupère toutes les entités

            foreach (CL_Association ass in myAssociations)
            {
                //Ajoute ses attributs
                data = controller.m_objets.Item3.afficheContenuMLDof(ass, controller.m_objets.Item2, controller.m_objets.Item1);
                data.Sort(CL_DictionnaireDeDonnees.idComparaison);
                if (data.Count > 0)
                {
                    //Créé la table correspondante 
                    myXmlTextWriter.WriteStartElement("TABLE", null);
                    //myXmlTextWriter.WriteAttributeString("id", ass.Id);
                    myXmlTextWriter.WriteAttributeString("name", ass.Name);
                    myXmlTextWriter.WriteAttributeString("codeName", ass.CodeName);


                    foreach (CL_DictionnaireDeDonnees d in data)
                    {
                        myXmlTextWriter.WriteStartElement("ATTRIBUT", null);
                        //myXmlTextWriter.WriteAttributeString("id", d.id.ToString());
                        myXmlTextWriter.WriteAttributeString("nom", d.nom);
                        myXmlTextWriter.WriteAttributeString("code", d.code);
                        myXmlTextWriter.WriteAttributeString("type", d.stringType);
                        myXmlTextWriter.WriteAttributeString("Required", d.O.ToString());
                        if (d.isForeignKey)
                        {
                            myXmlTextWriter.WriteAttributeString("FOREIGN_KEY_OF", !d.AssoIsNull() ? controller.getAssociation(d.idAsso).Name : (!d.EntIsNull() ? controller.getEntite(d.idEntite).Name : null));
                        }
                        else
                        {
                            if (d.pk) myXmlTextWriter.WriteAttributeString("PRIMARY_KEY_OF", controller.getAssociation(d.idAsso).Name);
                        }

                        myXmlTextWriter.WriteEndElement();
                    }
                    myXmlTextWriter.WriteEndElement();
                }
            }

            #endregion

            myXmlTextWriter.WriteEndElement();//End MLD

            myXmlTextWriter.Flush();
            myXmlTextWriter.Close();
        }

        /// <summary>
        /// Retourne un String aléatoire
        /// </summary>
        /// <param name="size"></param>
        /// <param name="lowerCase"></param>
        /// <returns></returns>
        public string RandomString(int size, bool lowerCase)
        {
            StringBuilder builder = new StringBuilder();
            Random random = new Random();
            char ch;
            for (int i = 0; i < size; i++)
            {
                ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
                builder.Append(ch);
            }
            if (lowerCase)
                return builder.ToString().ToLower();
            return builder.ToString();
        }
    }
}
